package org.csu.mypetstore.controller;

//import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Result;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/signonForm")
    public String signonForm(){
        return "account/signonForm";
    }

    @GetMapping("/code")
    @ResponseBody
    public boolean getCode(@RequestParam("phone") String phone, HttpSession session){
        try {
            //随机生成验证码
            String code = String.valueOf(new Random().nextInt(999999));
            //将验证码通过榛子云接口发送至手机
            ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "111132", "9289cbd0-146a-49e7-8585-a2c8eac22685");
            Map<String, Object> params = new HashMap<>();
            params.put("number", phone);
            params.put("templateId", "8534");
            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "5";
            params.put("templateParams", templateParams);
            String result = client.send(params);
//            String result = client.send(phone,"您的验证码为:"+code+"，该码有效期为5分钟，该码只能使用一次！");
            //获取验证码
            JSONObject json = JSONObject.parseObject(result);
            //将验证码存到session中,同时存入创建时间
            json.put("phone",phone);
            json.put("pcode",code);
            json.put("createTime",System.currentTimeMillis());
            System.out.println("验证码信息"+json);
            // 将认证码存入SESSION
            session.setAttribute("jsoncode",json);
            session.setAttribute("pCode",code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @PostMapping("/sigon")
    public void sigon(HttpServletResponse resp, HttpServletRequest req,@RequestParam("username") String username, @RequestParam("password") String password,
                      @RequestParam("vCode") String vCode,int isclick,Model model,HttpSession session) throws IOException {
        JSONObject UserCode = (JSONObject) session.getAttribute("code");
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        //用户名检测
        if(username==null||username.equals("")){
            //用户名为空
            result.setCode(0);
            result.setMsg("null");
        }else if(username!=null&&!username.equals("")){
            Account tempAccount = accountService.getAccount(username);
            if(tempAccount!=null){
                //用户名存在,且密码不为空
                if(password!=null&&!password.equals("")){
                    //将用户输入的密码进行加盐混淆，和混淆后的结果进行对比
                    String md5="";
                    try {
                        md5=MD5Util.getMD5String(password);
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
                    Account account=accountService.getAccount(username,md5);
                    if(account!=null){
                        if(vCode!=null){
                            String TrueCode= (String) session.getAttribute("pCode");
                            if(TrueCode!=null){
                                if(TrueCode.equalsIgnoreCase(vCode)){
                                    if(isclick==1){
                                        model.addAttribute("account",account);
                                        session.setAttribute("account",account);
                                        model.addAttribute("isok","signon");
                                        result.setCode(1);
                                        result.setMsg("success");
                                    }else{
                                        //验证码正确
                                        result.setCode(6);
                                        result.setMsg("success");
                                    }
                                }else {
                                    //验证码错误
                                    result.setCode(2);
                                    result.setMsg("code error");
                                }
                            }else {
                                System.out.println("还未发送验证码");
                            }
                        }else{
                            System.out.println("还未填写验证码");
                        }
                    }else{
                        //密码错误
                        result.setCode(3);
                        result.setMsg("password error");
                    }
                }else{
                    //用户名存在
                    result.setCode(4);
                    result.setMsg("Exist");
                }
            }else {
                //用户名不存在
                result.setCode(5);
                result.setMsg("Not Exist");
            }
        }
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/signOff")
    public String signOff(HttpSession session, Model model,SessionStatus sessionStatus){
        session.removeAttribute("account");
        sessionStatus.setComplete();
        return "catalog/main";
    }
    @GetMapping("/newAccountForm")
    public String newAccountForm(){
        return "account/newAccountForm";
    }

    @PostMapping("/newAccount")
    public void newAccount(HttpServletResponse resp, HttpServletRequest req,@RequestParam("username") String username, @RequestParam("password") String password,
                           @RequestParam("repeatedPassword") String repeatedPassword, @RequestParam("vCode") String vCode,
                           @RequestParam("firstName") String firstName,@RequestParam("lastName") String lastName,@RequestParam("email") String email,
                           @RequestParam("phone") String phone,@RequestParam("address1") String address1,@RequestParam("address2") String address2,
                           @RequestParam("city") String city,@RequestParam("state") String state,@RequestParam("zip") String zip,
                           @RequestParam("country") String country,@RequestParam("languagePreference") String languagePreference,
                           @RequestParam("favouriteCategoryId") String favouriteCategoryId,
                           @RequestParam("listOption") String listOption,
                           @RequestParam("bannerOption") String bannerOption, int isclick,
                           Model model) throws IOException, NoSuchAlgorithmException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        //用户名检测
        if(username==null||username.equals("")){
            //用户名为空
            result.setCode(0);
            result.setMsg("null");
        }else if(username!=null&&!username.equals("")){
            Account tempAccount = accountService.getAccount(username);
            if(tempAccount!=null){
                //用户名存在，不可使用
                result.setCode(1);
                result.setMsg("Exist");
            }else {
                //用户名不存在，密码不为空
                if(password!=null&&!password.equals("")){
                    HttpSession session=req.getSession();
                    String str=(String)session.getAttribute("checkcode");
                    if(str.equalsIgnoreCase(vCode)){
                        System.out.println("第二次调用");
                        //验证码正确
                        if(isclick==1){
                            Account account1 = new Account();
                            account1.setUsername(username);
                            //密码加盐混淆，保存到数据库中
                            try{
                                account1.setPassword(MD5Util.getMD5String(password));
                            }catch (NoSuchAlgorithmException e){
                                e.printStackTrace();
                            }
                            account1.setEmail(email);
                            account1.setPhone(phone);
                            account1.setAddress1(address1);
                            account1.setAddress2(address2);
                            account1.setCity(city);
                            account1.setState(state);
                            account1.setZip(zip);
                            account1.setCountry(country);
                            account1.setLanguagePreference(languagePreference);
                            account1.setFavouriteCategoryId(favouriteCategoryId);
                            account1.setListOption(Boolean.parseBoolean(listOption));
                            account1.setBannerOption(Boolean.parseBoolean(bannerOption));
                            accountService.insertAccount(account1);
                            result.setCode(2);
                            result.setMsg("success");
                        }else{
                            result.setCode(5);
                            result.setMsg("success");
                        }


                    }else{
                        System.out.println("第一次调用");
                        result.setCode(3);
                        result.setMsg("failed");
                    }
                }else{
                    result.setCode(4);
                    result.setMsg("Not Exist");
                }

            }
        }
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/verificationCode")
    public void VerificationCode(HttpServletResponse response,HttpServletRequest request,Model model) throws IOException {
        response.setContentType("image/jpeg");
        HttpSession session=request.getSession();
        int width=60;
        int height=20;

        //设置浏览器不要缓存此图片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //创建内存图像并获得图形上下文
        BufferedImage image=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics g=image.getGraphics();

        /*
         * 产生随机验证码
         * 定义验证码的字符表
         */
        String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands=new char[4];
        for(int i=0;i<4;i++){
            int rand=(int) (Math.random() *36);
            rands[i]=chars.charAt(rand);
        }

        /*
         * 产生图像
         * 画背景
         */
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);

        /*
         * 随机产生120个干扰点
         */

        for(int i=0;i<120;i++){
            int x=(int)(Math.random()*width);
            int y=(int)(Math.random()*height);
            int red=(int)(Math.random()*255);
            int green=(int)(Math.random()*255);
            int blue=(int)(Math.random()*255);
            g.setColor(new Color(red,green,blue));
            g.drawOval(x, y, 1, 0);
        }
        g.setColor(Color.BLACK);
        g.setFont(new Font(null, Font.ITALIC|Font.BOLD,18));

        //在不同高度输出验证码的不同字符
        g.drawString(""+rands[0], 1, 17);
        g.drawString(""+rands[1], 16, 15);
        g.drawString(""+rands[2], 31, 18);
        g.drawString(""+rands[3], 46, 16);
        g.dispose();

        //将图像传到客户端
        ServletOutputStream sos=response.getOutputStream();
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        byte[] buffer=baos.toByteArray();
        response.setContentLength(buffer.length);
        sos.write(buffer);
        baos.close();
        sos.close();

        session.setAttribute("checkcode", new String(rands));
        model.addAttribute("checkcode",new String(rands));
    }

    @GetMapping("editAccountForm")
    public String editAccountForm(){
        return "account/editAccountForm";
    }
    @PostMapping("editAccount")
    public String editAccount(HttpServletRequest request,HttpServletResponse response,@RequestParam("listOption") String listOption,
                              @RequestParam("bannerOption") String bannerOption,Model model) throws UnsupportedEncodingException {
        HttpSession session = request.getSession();
        Account account1=(Account) session.getAttribute("account");
        request.setCharacterEncoding("UTF-8");
//         System.out.println("++++++++++++++"+account1.getUsername());
        String username = account1.getUsername();
        String password = request.getParameter("password");
        String md5="";
        try {
            md5=MD5Util.getMD5String(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
//        System.out.println("++++++++++"+password);
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address1 = request.getParameter("address1");
        String address2 = request.getParameter("address2");
        String city = request.getParameter("city");
        String state = request.getParameter("state");
        String zip = request.getParameter("zip");
        String country = request.getParameter("country");
        String languagePreference = request.getParameter("languagePreference");
        String favouriteCategoryId = request.getParameter("favouriteCategoryId");
        Account account=new Account();
        account.setUsername(username);
        account.setPassword(md5);
        account.setFirstName(firstName);
        account.setLastName(lastName);
        account.setEmail(email);
        account.setPhone(phone);
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setCity(city);
        account.setState(state);
        account.setZip(zip);
        account.setCountry(country);
        account.setLanguagePreference(languagePreference);
        account.setFavouriteCategoryId(favouriteCategoryId);
        account.setListOption(Boolean.parseBoolean(listOption));
        account.setBannerOption(Boolean.parseBoolean(bannerOption));

        accountService.updateAccount(account);
        session.setAttribute("account",account);
        model.addAttribute("account",account);
        return "account/editAccountForm";
    }

    @GetMapping("/help")
    public String help(){
        return "common/help";
    }
}